package com.atguigu.web;

import com.atguigu.pojo.Book;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.Page;
import com.atguigu.pojo.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.OrderServiceImpl;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.test.UserServletTest;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author YAO
 * @create 2021-04-26 15:44
 */
@WebServlet(name = "UserServlet", value = "/userServlet")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    private OrderService orderService = new OrderServiceImpl();

    /**
     * 处理登录的功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        // 如果等于null,说明登录 失败!
        if (loginUser == null) {
            // 把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("username",username);

            //   跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            // 登录 成功
            //保存用户登录的信息到session
            req.getSession().setAttribute("user",loginUser);
            //如果登录的是管理员用户则跳转到管理员页面
            if("admin".equals(loginUser.getUsername())){
                resp.sendRedirect(req.getContextPath() + "/pages/manager/manager.jsp");
                return;
            }
            //跳到成功页面login_success.html
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }

    }

    /**
     * 处理登出的功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、销毁 Session 中用户登录的信息（或者销毁 Session）
        req.getSession().invalidate();
//        2、重定向到首页（或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 处理注册的功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), User.class);


//        2、检查 验证码是否正确  === 写死,要求验证码为:abcde
        if (token!= null && token.equalsIgnoreCase(code)) {
//        3、检查 用户名是否可用
            if (userService.existsUsername(username)) {

                System.out.println("用户名[" + username + "]已存在!");
                //把回显信息。保存到Request域中
                req.setAttribute("msg","用户名已存在！");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
//        跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //      可用
//                调用Sservice保存到数据库
                userService.registUser(new User(null, username, password, email));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //把回显信息。保存到Request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先设置响应乱码问题
        resp.setContentType("text/html; charset=UTF-8");
        //获取请求的参数
        String username = req.getParameter("username");
        //调用UserService.existsUsername()
        boolean existsUsername = userService.existsUsername(username);
        if("".equals(username)){
            existsUsername = true;
        }
        // 把返回的结果封装成map对象
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("existsUsername",existsUsername);
        Map<String, Object> resMap = WebUtils.ToResultMap(dataMap, "查询用户名成功!", 200);


        //将结果转成json字符串传回客户端
        Gson gson = new Gson();
        String resJson = gson.toJson(resMap);
        resp.getWriter().write(resJson);
    }


    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取请求的参数 pageNo pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        // 2.调用bookService.page() 返回page对象
        Page<User> page = userService.page(pageNo, pageSize);

        page.setUrl("userServlet?action=page");

        // 3.保存page对象到request域中
        req.setAttribute("page",page);
        // 4.请求转发到page/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/manager/user_manager.jsp").forward(req,resp);

    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求的参数用户id
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //删除用户之前删除该用户所属订单的订单小项
        List<Order> orders = orderService.showMyOrders(id);
        for (Order order : orders) {
            String orderId = order.getOrderId();
            //删除该订单的订单小项
            orderService.deleteOrderItemsByOrderId(orderId);
        }
        //删除用户之前删除该用户所属订单
        orderService.deleteOrdersByUserId(id);
        //2. 调用userServlet.deleteUserById();删除用户
        userService.deleteUserById(id);
        //3. 重定向回图书列表管理页面
        //      /book/manager/bookServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/userServlet?action=page&pageNo=" + req.getParameter("pageNo"));

    }


    protected void getUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求的参数用户编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //2. 调用userService.queryUserById查询图书
        User user = userService.queryUserById(id);
        //3. 保存到图书Request域中
        req.setAttribute("user",user);
        //4. 请求转发到 pages/manager/book_edit.jsp页面
        req.getRequestDispatcher("/pages/manager/user_edit.jsp").forward(req,resp);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数列表
        Map<String, String[]> map = req.getParameterMap();
        //调用工具类返回一个user对象
        User user = WebUtils.copyParamToBean(map, User.class);
        //调用userService.update方法
        userService.update(user);
        resp.sendRedirect(req.getContextPath() + "/userServlet?action=page&pageNo="
                + req.getParameter("pageNo"));

    }

    protected void findPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名
        String username = req.getParameter("username");
        String pwd = "";
        //查找该用户
        boolean existsUsername = userService.existsUsername(username);
        if(existsUsername){
            User user = userService.findPwdByUsername(username);
            if(user != null){
                pwd = user.getPassword();
            }
        }
        //保存密码
        req.setAttribute("pwd",pwd);
        //跳转
        req.getRequestDispatcher("/pages/user/pwd.jsp").forward(req,resp);
    }


}
